package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/v1/file")
public class UploadController {
	
	/**
	 * 文件上传功能
	 */
	@PostMapping("/upload")
	public JsonResult upload(MultipartFile file) throws IOException {
        /*
            1.接收客户端传递的文件;
            2.将文件保存到服务器中;
            3.返回成功信息给客户端;
         */
		//终极目标: d:/files/zly.jpg
		//1.获取原始文件名: zly.jpg;
		String filename = file.getOriginalFilename();
		//2.获取文件名后缀: .jpg;
		String suffix = filename.substring(filename.lastIndexOf("."));
		//3.处理文件名: 20714d37-a89b-4a3e-8b8b-7394ee85d418.jpg
		filename = UUID.randomUUID() + suffix;
		SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
		String datePath = sdf.format(new Date());
		String staticPath = "D:/files";
		File dirFile = new File(staticPath + datePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		String path = staticPath + datePath + filename;
		file.transferTo(new File(path));
		
		
		return JsonResult.ok();
	}
}

